package cn.edu.cuit.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.cuit.bean.User;

/**
 * @author fhzheng
 * <h1> 登录控制器 </h1>
 * <li> 1 完成中文乱码处理
 * <li> 2 完成用户登录参数获取
 * <li> 3 完成用户会话对象获取
 * <li> 4 完成用户会话中的属性的保持，再跳转
 */
public class LoginServlet extends HttpServlet {

	// java基础复习：Java的序列化机制是通过判断类的serialVersionUID来验证版本一致性的。
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
	}
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("LoginServlet working...");
		// 处理中文乱码
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		// 获取用户参数
		String name = request.getParameter("name");
		String pass = request.getParameter("pass");
		// 封装数据到javabean
		User user = new User(name,pass);
		// 创建session，这个动作会触发监听【有用户访问 ，则会创建相应的session】
		HttpSession session = ((HttpServletRequest) request).getSession();
		// 置值【在用户session中创建属性，会触发发相应的监听】，供跳转以后再用
		session.setAttribute("user", user);
		// 跳转，以转发的方式在服务器内完成跳转
		request.getRequestDispatcher("/admin/index.jsp").forward(request, response);
	}

	public void init() throws ServletException {
	}

}
